package com.ruoyi.system.service.impl;

import com.ruoyi.common.OrderNumUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.*;
import com.ruoyi.system.mapper.CommunityMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.app.CardMapper;
import com.ruoyi.system.mapper.app.OrderCardChargeMapper;
import com.ruoyi.system.mapper.app.OrderMapper;
import com.ruoyi.system.service.CardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class CardServiceImpl implements CardService {

    @Autowired
    CardMapper cardMapper;
    @Autowired
    CommunityMapper communityMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderCardChargeMapper orderCardChargeMapper;

    @Override
    public String importUser(List<Card> cardList, boolean updateSupport) {
        if (StringUtils.isNull(cardList) || cardList.size() == 0) {
            throw new ServiceException("导入电卡数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Card card : cardList) {

            try {
                // 验证是否存在这个用户
                Card check = cardMapper.selectByNum(card.getCardNum());

                if (StringUtils.isNull(check)) {

                    this.addCard(card);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、电池 " + card.getCardNum() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、电池 " + card.getCardNum() + " 已存在");
                }


            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、电池 " + card.getCardNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void addCard(Card card) {
        Card check =cardMapper.selectByNum(card.getCardNum().trim());
        if (StringUtils.isNotNull(check)) {
            throw new ServiceException("卡号已存在！");
        }
        card.setCardNum(card.getCardNum().trim());
        card.setCreateTime(new Date());
        if (card.getCommunityName() != null) {
            Community community = communityMapper.selectByName(card.getCommunityName());
            if (StringUtils.isNotNull(community)) {
                card.setCommunityId(community.getId());
                card.setOperatorName(community.getOperatorName());
                card.setOperatorId(card.getOperatorId());
            }
        }
        cardMapper.insertSelective(card);
    }

    @Override
    public void delCard(Long cardId) {
        Card card = cardMapper.selectByPrimaryKey(cardId);
        if (StringUtils.isNull(cardId)) {
            throw new ServiceException("电卡不存在");
        }
        if (StringUtils.isNotNull(card.getUserId())) {
            throw new ServiceException("电卡绑定用户，解绑后在操作。");
        }
        cardMapper.deleteByPrimaryKey(cardId);

    }

    @Override
    public void setCard(Card card) {
        cardMapper.updateByPrimaryKey(card);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Card> cardList(Card card) {
        return cardMapper.cardList(card);
    }

    @Override
    public List<Map> operatorCommunityList(String operatorName) {
        return communityMapper.operatorCommunityList(operatorName);
    }

    @Override
    public void cardCharge(Long cardId, BigDecimal money) {
        Card card = cardMapper.selectByPrimaryKey(cardId);

        if (money.doubleValue() < 0&&(card.getMoney().add(card.getDiscountsMoney()).doubleValue() + money.doubleValue() < 0) ) {
            throw new ServiceException("减去金额过大！");
        }
        //添加订单
        Order order = new Order();
        if (StringUtils.isNotNull(card.getUserId())) {
            User user = userMapper.selectByPrimaryKey(card.getUserId());
            order.setUserId(user.getId());
            order.setUserName(user.getUsername());
            order.setUserPhone(user.getPhone());
        }
        order.setCommunityId(card.getCommunityId());
        order.setCommunityName(card.getCommunityName());
        order.setOperatorId(card.getOperatorId());
        order.setOperatorName(card.getOperatorName());
        order.setOrderNo(OrderNumUtil.getOrderNum());
        order.setWxOrderNo("管理员充值,充值人员："+ SecurityUtils.getLoginUser().getUser().getUserName());
        order.setOrderType(3);
        order.setOrderState(1);
        order.setType(0);
        order.setCreateTime(new Date());
        order.setMoney(money);
        orderMapper.insertSelective(order);

        if (money.doubleValue() > 0) {
            card.setDiscountsMoney(card.getDiscountsMoney().add(money));
        }else {
            if (card.getDiscountsMoney().doubleValue() > money.doubleValue()) {
                card.setDiscountsMoney(card.getDiscountsMoney().add(money));
            }
            else {
                money = money.add(card.getDiscountsMoney());
                card.setMoney(card.getMoney().add(money));
                card.setDiscountsMoney(new BigDecimal("0"));
            }
        }


        OrderCardCharge orderCardCharge = new OrderCardCharge();
        orderCardCharge.setChargeMoney(new BigDecimal("0"));
        orderCardCharge.setDiscountMoney(money);
        orderCardCharge.setCardNum(card.getCardNum());
        orderCardCharge.setOrderId(order.getId());

        orderCardCharge.setChargeTime(new Date());
        orderCardCharge.setBeforeMoney(card.getMoney().add(card.getDiscountsMoney()));

        orderCardCharge.setAfterMoney(card.getMoney().add(card.getDiscountsMoney()));
        orderCardChargeMapper.insertSelective(orderCardCharge);
        cardMapper.updateByPrimaryKeySelective(card);
    }
}
